/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.agenda.model.persistence;

import com.agenda.model.repository.GenericRepository;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceException;


/**
 *
 * @author ronildo
 */
public class GenericDAO <T, DAOImpl extends GenericRepository> implements GenericRepository<T>{

    
    protected EntityManager em;

    public DAOImpl setEntityManager(EntityManager em){
        this.em = em;
        return (DAOImpl)this;
    }

    public void persist(T entity){
        try{
            em.persist(entity);
        }catch(PersistenceException e){
            throw new DAOException(e);
        }
    }

    public void update(T entity){
        try{
            em.merge(entity);
        }catch(PersistenceException e){
            e.printStackTrace();
            throw new DAOException(e);
        }
    }

    public void remove(T entity, Long id){
        try{
            em.remove( em.getReference( entity.getClass() , id) );
        }catch(EntityNotFoundException e){
            e.printStackTrace();
        }catch(PersistenceException e){
            e.printStackTrace();
            throw new DAOException(e);
        }
    }
}
